package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.entity.UserHolder;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author syf
 * @version 1.0
 * @date 2019/08/17 13:19
 * @Description TODO:
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String USER_CART_PRE="USER_CART_PRE";

    public void saveCart(Cart cart) {
        try {
            //得到当前用户购物车的id
            String key = USER_CART_PRE + UserHolder.getUserId();
            //当前用户已经有购物车了获取当前购物车信息
            BoundHashOperations<String, String, String> skuMap = redisTemplate.boundHashOps(key);
            //先判断购物车中是否有当前sku
            Boolean hasSku = skuMap.hasKey(cart.getSkuId().toString());
            if(hasSku!=null && hasSku){
                //得到当前购物车中当前sku信息
                String skuJsonStr = skuMap.get(cart.getSkuId().toString());
                Cart redisCart = JsonUtils.toBean(skuJsonStr, Cart.class);
                //把redis中的cart对象的数量合并到参数的cart对象中
                cart.setNum(cart.getNum()+redisCart.getNum());
            }
            //把cart放入到redis中【已经在购物车的，修改数量然后保存，没有在购物车的直接保存】
            skuMap.put(cart.getSkuId().toString(),JsonUtils.toString(cart));
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    //获取购物车
    public List<Cart> findCarts() {
        //得到当前用户购物车id
        String key = USER_CART_PRE + UserHolder.getUserId();
        //判断当前用户是否有购物车
        Boolean hasCart = redisTemplate.hasKey(key);
        if (hasCart ==null || !hasCart){
            //购物车不存在
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //判断redis中是否有值
        BoundHashOperations<String, String, String> skuMap = redisTemplate.boundHashOps(key);
        if (skuMap == null){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //得到购物车中所有cart的json格式的字符串
        List<String> values = skuMap.values();
        List<Cart> carts = values.stream()
                .map(value -> JsonUtils.toBean(value, Cart.class))//临时变量
                .collect(Collectors.toList());
        return carts;
    }

    /**
     * 合并购物车
     * @param carts
     */
    public void addCarts(List<Cart> carts) {
        for (Cart cart : carts) {
            saveCart(cart);
        }
    }
}
